<template>
    <div class="marketing_coupon_add">
        <el-form label-width="120px" :model="form" :rules="rules" ref="addForm">
            <div class="form_content">
                <el-card class="base_card">
                    <template #header>基础设置</template>
                    <el-row>
                        <el-col>
                            <el-form-item label="优惠券名称" prop="couponName">
                                <el-input
                                    v-model="form.couponName"
                                    maxlength="30"
                                    show-word-limit
                                    clearable
                                    placeholder="仅用于后台展示"
                                    autocomplete="off" />
                            </el-form-item>
                        </el-col>
                        <el-col>
                            <el-form-item
                                label="优惠券标题"
                                prop="couponTitle"
                                @mouseover="handleMouseover"
                                @mouseleave="handleMouseleave">
                                <el-input
                                    v-model="form.couponTitle"
                                    maxlength="10"
                                    show-word-limit
                                    clearable
                                    placeholder="展示在用户端"
                                    autocomplete="off"
                                    :disabled="isDisabled" />
                            </el-form-item>
                        </el-col>
                        <el-col>
                            <el-form-item label="发放总量" prop="couponTotal">
                                <el-input-number
                                    placeholder="请输入"
                                    class="mw108"
                                    v-model="form.couponTotal"
                                    :precision="0"
                                    :step="1"
                                    :value-on-clear="null"
                                    :min="1"
                                    :max="100000000"
                                    :controls="false" /><span class="unit-span">张</span>
                                <div class="coupon-total-tip">优惠券生效后发放总量只能增加不能减少，请谨慎设置</div>
                            </el-form-item>
                        </el-col>
                        <!-- todo:校验根据优惠券类型 -->
                        <el-col>
                            <el-form-item label="优惠内容" prop="couponDiscountContent">
                                <div v-if="couponType == 1">
                                    <span class="mr8">减免</span>
                                    <el-input-number
                                        placeholder="请输入"
                                        class="mw108"
                                        v-model="form.couponDiscountContent"
                                        :precision="2"
                                        :step="0.01"
                                        :min="0.01"
                                        :max="99999.99"
                                        :controls="false"
                                        :disabled="isDisabled"
                                        @mouseover="handleMouseover"
                                        @mouseleave="handleMouseleave" />
                                    <span class="ml8">元</span>
                                </div>
                                <div v-else>
                                    <span class="mr8">打</span>
                                    <el-input-number
                                        placeholder="请输入"
                                        v-model="form.couponDiscountContent"
                                        :precision="1"
                                        :step="0.1"
                                        :min="0.1"
                                        :max="9.9"
                                        :controls="false"
                                        :disabled="isDisabled"
                                        @mouseover="handleMouseover"
                                        @mouseleave="handleMouseleave" />
                                    <span class="ml8">折</span>
                                    <!-- todo:选中 -->
                                    <div class="custom-discount">
                                        <el-checkbox
                                            v-model="form.couponDiscountMostChecked"
                                            class="mr8"
                                            :disabled="isDisabled"
                                            @change="couponDiscountMostCheckedChange"
                                            @mouseover="handleMouseover"
                                            @mouseleave="handleMouseleave"></el-checkbox>
                                        <!-- todo:未选中禁用 -->
                                        <div class="most_block">
                                            最高优惠
                                            <el-input-number
                                                placeholder="请输入"
                                                :disabled="isDisabled || !form.couponDiscountMostChecked"
                                                v-model="form.couponDiscountMost"
                                                :precision="2"
                                                :step="0.01"
                                                :min="0.01"
                                                :max="99999.99"
                                                :controls="false"
                                                @mouseover="handleMouseover"
                                                @mouseleave="handleMouseleave" />
                                            <span class="ml8">元</span>
                                        </div>
                                    </div>
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col>
                            <el-form-item label="使用门槛" prop="couponPrerequisites">
                                <el-radio-group
                                    :disabled="isDisabled"
                                    class="d_flex dis_flex"
                                    v-model="form.couponPrerequisites"
                                    @change="couponPrerequisitesChange"
                                    @mouseover="handleMouseover"
                                    @mouseleave="handleMouseleave">
                                    <el-radio :label="2" :class="{ 'coupon-prerequisites-radio': couponType != 1 }">
                                        <template #default>
                                            <span class="mr8">订单商品金额满</span>
                                            <el-form-item prop="couponPrerequisites2">
                                                <el-input-number
                                                    placeholder="请输入"
                                                    :disabled="isDisabled || form.couponPrerequisites != 2"
                                                    v-model="form.couponPrerequisitesAdditional2"
                                                    :precision="2"
                                                    :step="0.01"
                                                    :min="0.01"
                                                    :max="99999.99"
                                                    :controls="false"
                                                    @change="couponPrerequisitesAdditional2Change" /><span class="ml8"
                                                    >元，可用</span
                                                >
                                            </el-form-item>
                                        </template>
                                    </el-radio>
                                    <div class="coupon-prerequisites-checkbox" v-if="couponType == 1">
                                        <el-checkbox
                                            :disabled="isDisabled || form.couponPrerequisites != 2"
                                            :true-label="2"
                                            :false-label="1"
                                            v-model="form.couponEveryDecrease"
                                            label="每满即减（循环满减）" />
                                    </div>
                                    <el-radio :label="3">
                                        <template #default>
                                            <span class="mr8">订单商品件数满</span>
                                            <el-form-item prop="couponPrerequisites3">
                                                <el-input-number
                                                    :disabled="isDisabled || form.couponPrerequisites != 3"
                                                    placeholder="请输入"
                                                    v-model="form.couponPrerequisitesAdditional3"
                                                    :precision="0"
                                                    :step="1"
                                                    :min="1"
                                                    :max="100000000"
                                                    :controls="false" /><span class="ml8">件，可用</span>
                                            </el-form-item>
                                        </template>
                                    </el-radio>
                                    <el-radio :label="1">无门槛</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col>
                            <el-form-item
                                label="用券时间"
                                prop="couponTimeType"
                                @mouseover="handleMouseover"
                                @mouseleave="handleMouseleave">
                                <el-radio-group
                                    class="dis_flex"
                                    :disabled="isDisabled"
                                    v-model="form.couponTimeType"
                                    @change="couponTimeTypeChange">
                                    <el-radio class="mb16" :label="1">
                                        <el-form-item prop="couponTimeAt">
                                            <el-date-picker
                                                v-model="form.couponTimeAt"
                                                type="datetimerange"
                                                range-separator="至"
                                                :default-time="defaultTime"
                                                start-placeholder="开始时间"
                                                end-placeholder="结束时间"
                                                :disabled="isDisabled || form.couponTimeType != 1"
                                                :disabled-date="disabledDate" />
                                        </el-form-item>
                                    </el-radio>
                                    <el-radio class="d_flex_center" :label="2">
                                        <span class="mr8">领券后</span>
                                        <!-- todo:禁用 -->
                                        <el-select
                                            class="mw90"
                                            style="margin-top: -2px"
                                            v-model="form.couponReceiveTimeTypeVal"
                                            :disabled="isDisabled || form.couponTimeType != 2">
                                            <el-option
                                                v-for="(item, key) in couponReceiveTimeType"
                                                :key="key"
                                                :label="item.label"
                                                :value="item.value / 1">
                                                {{ item.label }}
                                            </el-option> </el-select
                                        ><span class="ml8 mr8">生效，</span>
                                        <el-form-item prop="couponTimeValue">
                                            <el-input-number
                                                class="mw90"
                                                placeholder="请输入"
                                                v-model="form.couponTimeValue"
                                                :disabled="isDisabled || form.couponTimeType != 2"
                                                :precision="0"
                                                :step="1"
                                                :min="1"
                                                :max="1000"
                                                :controls="false" /><span class="ml8">天内可用</span>
                                        </el-form-item>
                                    </el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col>
                            <el-form-item label="适用商品" prop="couponMatch">
                                <el-radio-group
                                    v-model="form.couponMatch"
                                    @change="goodTypeChange"
                                    @mouseover="handleMouseover"
                                    @mouseleave="handleMouseleave"
                                    :disabled="isDisabled">
                                    <div
                                        class="activity-good-type"
                                        v-for="(item, index) in couponMatchTypeCopy"
                                        :class="{ mb8: index !== couponMatchTypeCopy?.length - 1 }"
                                        :key="item.value">
                                        <el-radio :label="item.value">
                                            {{ item.label }}
                                        </el-radio>
                                        <!-- 弹窗 -->
                                        <ZwGeneralGoods
                                            :disabled="isDisabled"
                                            style="margin-left: -14px"
                                            v-if="item.value != 1 && form.couponMatch == item.value"
                                            :value="form.goods"
                                            :isMulti="true"
                                            @handle-confirm="getGoodData" />
                                        <!-- <SelectedGoods
                                            @mouseover.stop
                                            @mouseleave.stop
                                            v-if="item.value != 1 && form.couponMatch == item.value"
                                            :disabled="isDisabled"
                                            :value="form.goods"
                                            @handle-remove="handleRemoveGood"></SelectedGoods> -->
                                        <ZwSelectedGoods
                                            @mouseover.stop
                                            @mouseleave.stop
                                            v-if="item.value != 1 && form.couponMatch == item.value"
                                            :disabled="isDisabled"
                                            :value="form.goods"
                                            :customTitle="item.value == 2 ? '以下商品可用' : '以下商品不可用'"
                                            @handle-remove="handleRemoveGood"></ZwSelectedGoods>
                                    </div>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>
                <el-card class="last-card">
                    <template #header>发放和使用规则</template>
                    <el-row>
                        <el-col>
                            <el-form-item
                                v-for="{ label, checkboxLabel, prop, tip } in advancedList"
                                :label="label"
                                :prop="prop"
                                :key="label">
                                <template v-if="prop === 'couponAcquireLimitType'">
                                    <el-radio-group
                                        :disabled="isDisabled"
                                        class="d_flex dis_flex"
                                        v-model="form.couponAcquireLimitType"
                                        @change="couponAcquireLimitTypeChange"
                                        @mouseover="handleMouseover"
                                        @mouseleave="handleMouseleave">
                                        <el-radio :label="1" class="mb16">每人领取次数不限</el-radio>
                                        <el-radio :label="2">
                                            <template #default>
                                                <span class="mr8">每人最多可领</span>
                                                <el-form-item prop="couponAcquireLimit">
                                                    <el-input-number
                                                        placeholder="请输入"
                                                        :disabled="isDisabled || form.couponAcquireLimitType != 2"
                                                        v-model="form.couponAcquireLimit"
                                                        :precision="0"
                                                        :step="1"
                                                        :min="1"
                                                        :max="100"
                                                        :controls="false" />
                                                </el-form-item>
                                                <span class="ml8">张</span>
                                            </template>
                                        </el-radio>
                                    </el-radio-group>
                                </template>
                                <template v-if="prop === 'couponDescription'">
                                    <el-input
                                        class="mw440"
                                        type="textarea"
                                        placeholder="优惠券使用说明将展示给用户，请谨慎填写"
                                        maxlength="200"
                                        :rows="4"
                                        show-word-limit
                                        v-model="form.couponDescription"
                                        autocomplete="off" />
                                </template>
                                <template v-if="!['couponAcquireLimitType', 'couponDescription'].includes(prop)">
                                    <el-checkbox
                                        v-model="form[prop]"
                                        :true-label="2"
                                        :false-label="1"
                                        :disabled="isDisabled"
                                        @mouseover="handleMouseover"
                                        @mouseleave="handleMouseleave"
                                        >{{ checkboxLabel }}</el-checkbox
                                    >
                                </template>
                                <div v-if="tip" class="custom-tip" v-html="tip"></div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>
            </div>
            <div class="form-footer">
                <div>
                    <el-button @click="cancelHandler">取消</el-button>
                    <el-button type="primary" @click="saveHandler">保存</el-button>
                </div>
            </div>
        </el-form>
        <!-- tooltip提示框 -->
        <el-tooltip
            popper-class="custom-tooltip-class"
            v-model:visible="tooltipVisible"
            content="优惠券已启用，不支持编辑"
            placement="top"
            trigger="click"
            virtual-triggering
            :virtual-ref="triggerRef" />
        <!-- 弹窗 -->
        <ConflictDialog ref="conflictDialog"></ConflictDialog>
    </div>
</template>

<script setup>
import { ref, unref, reactive, computed, onMounted, onUnmounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import request from '@/request/index';
import constants from '@/commons/constants';
import { ElMessage } from 'element-plus';
import {
    isDayBefore,
    dateDiff,
    cloneDeep,
    format,
    isEmpty,
    packSelectObjUtil,
    floatMultiply,
    floatDivide
} from '@/commons/utils';
import { setLayout, resetLayout } from '@/hooks/layout';
import ConflictDialog from './conflictDialog.vue';
import { debounce } from 'lodash';

const activityGoodType = reactive(packSelectObjUtil(constants.ACTIVITY_GOOD_MATCH));
const couponMatchTypeCopy = [activityGoodType[1], activityGoodType[2], activityGoodType[0]];
const couponReceiveTimeType = reactive(packSelectObjUtil(constants.COUPON_RECEIVE_TIME_TYPE));

const router = useRouter();
const route = useRoute();

const isPageLoading = ref(false);
const conflictDialog = ref(null);
const addForm = ref(null);
const position = ref({
    top: 0,
    left: 0,
    bottom: 0,
    right: 0
});
const triggerRef = ref({
    getBoundingClientRect() {
        return position.value;
    }
});
let tooltipVisible = ref(false);

const form = reactive({
    couponName: '',
    couponTitle: '',
    couponTotal: null,
    couponMatch: 2,
    couponPrerequisites: 2,
    couponPrerequisitesAdditional2: null, // 订单满x金额用
    couponPrerequisitesAdditional3: null, // 订单满x件用
    couponType: 1, // 类型
    couponEveryDecrease: 1, // 每满即减
    couponDiscountContent: null,
    couponDiscountMost: null, // 最高优惠
    couponTimeType: 1, // 用券类型
    couponTimeAt: [],
    couponTimeValue: null,
    couponAcquireLimitType: 1, // 限领/人
    couponAcquireLimit: null,
    couponPublic: 1,
    couponUsage: 1,
    couponDescription: '',
    goods: [],
    couponDiscountMostChecked: false, // 打折的情况下选中最高优惠
    couponReceiveTimeTypeVal: null // 用券时间类型
});
let formClone = reactive(cloneDeep(form));
// todo:获取值

const defaultTime = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)];
const disabledDate = date => {
    return isDayBefore(date);
};
const advancedList = [
    { label: '领取次数', prop: 'couponAcquireLimitType' },
    {
        label: '公开设置',
        prop: 'couponPublic',
        checkboxLabel: '允许公开领取优惠券',
        tip: '勾选后，符合条件的优惠券将展示在商品详情，用户可主动领取。'
    },
    // { label: '使用设置', prop: 'couponUsage', checkboxLabel: '优惠券仅原价购买商品时使用' },
    { label: '使用说明', prop: 'couponDescription' }
];

const checkCouponTotal = (rule, value, callback) => {
    if (!form.couponTotal) {
        return callback(new Error('请输入发放总量'));
    }
    if (form.couponTotal < 1 || form.couponTotal > 100000000) {
        return callback(new Error('请输入1~100000000的数值'));
    }
    // todo: couponStatus.value状态
    if (form.id && couponStatus.value == 6 && form.couponTotal < formClone.couponTotal) {
        return callback(new Error(`发放总量不得少于${formClone.couponTotal}张`));
    }
    callback();
};

const checkCouponDiscountContent = (rule, value, callback) => {
    if (couponType.value == 1) {
        if (!form.couponDiscountContent) {
            return callback(new Error('请输入减免值'));
        }
        if (
            form.couponPrerequisites == 2 &&
            ![null, undefined].includes(form.couponPrerequisitesAdditional2) &&
            form.couponDiscountContent >= form.couponPrerequisitesAdditional2
        ) {
            return callback(new Error('减免金额应小于使用门槛订单满额'));
        }
        if (form.couponDiscountContent < 0.01 || form.couponDiscountContent > 99999.99) {
            return callback(new Error('请输入0.01~99999.99的减免值'));
        }
        return callback();
    }
    if (couponType.value == 2) {
        if (!form.couponDiscountContent) {
            return callback(new Error('请输入打折值'));
        }
        if (form.couponDiscountContent < 0.1 || form.couponDiscountContent > 9.9) {
            return callback(new Error('请输入0.1~9.9的打折值'));
        }
        // todo:checkbox
        if (form.couponDiscountMostChecked && !form.couponDiscountMost) {
            if (!form.couponDiscountMost) {
                return callback(new Error('请输入最高优惠值'));
            }
            if (form.couponDiscountMost < 0.01 || form.couponDiscountMost > 99999.99) {
                return callback(new Error('请输入0.01~99999.99的最高优惠值'));
            }
        }
        return callback();
    }
    callback();
};
// const checkCouponPrerequisites = (rule, value, callback) => {
//     if (value == 2) {
//         if (!form.couponPrerequisitesAdditional2) {
//             return callback(new Error('请输入订单满额值'));
//         }
//         if (form.couponPrerequisitesAdditional2 < 0.01 || form.couponPrerequisitesAdditional2 > 99999.99) {
//             return callback(new Error('请输入0.01~99999.99的订单满额值'));
//         }
//         return callback();
//     }
//     if (value == 3) {
//         if (!form.couponPrerequisitesAdditional3) {
//             return callback(new Error('请输入订单满件数'));
//         }
//         if (form.couponPrerequisitesAdditional3 < 1 || form.couponPrerequisitesAdditional3 > 100000000) {
//             return callback(new Error('请输入1~100000000的订单满件数'));
//         }
//         return callback();
//     }
//     callback();
// };
const checkCouponPrerequisites2 = (rule, value, callback) => {
    if (form.couponPrerequisites == 2) {
        if (!form.couponPrerequisitesAdditional2) {
            return callback(new Error('请输入订单满额值'));
        }
        if (form.couponPrerequisitesAdditional2 < 0.01 || form.couponPrerequisitesAdditional2 > 99999.99) {
            return callback(new Error('请输入0.01~99999.99的订单满额值'));
        }
    }
    return callback();
};
const checkCouponPrerequisites3 = (rule, value, callback) => {
    if (form.couponPrerequisites == 3) {
        if (!form.couponPrerequisitesAdditional3) {
            return callback(new Error('请输入订单满件数'));
        }
        if (form.couponPrerequisitesAdditional3 < 1 || form.couponPrerequisitesAdditional3 > 100000000) {
            return callback(new Error('请输入1~100000000的订单满件数'));
        }
    }
    return callback();
};

const checkCouponTimeType = (rule, value, callback) => {
    if (value == 1) {
        if (!form.couponTimeAt || !form.couponTimeAt?.length || !form.couponTimeAt[0]) {
            return callback(new Error('请选择开始时间和结束时间'));
        }
        return callback();
    }
    if (value == 2) {
        if (!form.couponTimeValue) {
            return callback(new Error('请输入生效天数'));
        }
        if (form.couponTimeValue < 1 || form.couponTimeValue > 1000) {
            return callback(new Error('请输入1~1000的天数值'));
        }
        return callback();
    }
    callback();
};

const checkCouponTimeAt = (rule, value, callback) => {
    if (form.couponTimeType == 1) {
        if (!form.couponTimeAt || !form.couponTimeAt?.length || !form.couponTimeAt[0]) {
            return callback(new Error('请选择开始时间和结束时间'));
        }
        return callback();
    }
    callback();
};

const checkCouponTimeValuee = (rule, value, callback) => {
    if (form.couponTimeType == 2) {
        if (!form.couponTimeValue) {
            return callback(new Error('请输入生效天数'));
        }
        if (form.couponTimeValue < 1 || form.couponTimeValue > 1000) {
            return callback(new Error('请输入1~1000的天数值'));
        }
        return callback();
    }
    callback();
};

const checkGoods = (rule, value, callback) => {
    if ([2, 3].includes(form.couponMatch) && !form.goods?.length) {
        return callback(new Error(`指定商品${form.couponMatch == 3 ? '不' : ''}可用，必须选择商品`));
    }
    callback();
};

const checkAcquireLimit = (rule, value, callback) => {
    if (form.couponAcquireLimitType == 2) {
        if (!form.couponAcquireLimit) {
            return callback(new Error('请输入每人最多领取张数'));
        }
        if (form.couponAcquireLimit < 1 || form.couponAcquireLimit > 100) {
            return callback(new Error('请输入1~100的张数'));
        }
        return callback();
    }
    callback();
};

const rules = computed(() => {
    const baseRuleList = {
        couponName: [
            { required: true, message: '请输入优惠券名称', trigger: 'blur' },
            { max: 30, message: '最长不超过30个字', trigger: 'blur' }
        ],
        couponTitle: [
            { required: true, message: '请输入优惠券标题', trigger: 'blur' },
            { max: 10, message: '最长不超过10个字', trigger: 'blur' }
        ],
        couponTotal: [{ required: true, trigger: 'blur', validator: checkCouponTotal }],
        couponDiscountContent: [{ required: true, trigger: 'change', validator: checkCouponDiscountContent }],
        couponPrerequisites: [{ required: true }],
        couponPrerequisites2: [{ required: true, trigger: 'blur', validator: checkCouponPrerequisites2 }],
        couponPrerequisites3: [{ required: true, trigger: 'blur', validator: checkCouponPrerequisites3 }],
        couponTimeType: [{ required: true }],
        couponTimeAt: [{ required: true, trigger: 'change', validator: checkCouponTimeAt }],
        couponTimeValue: [{ required: true, trigger: 'blur', validator: checkCouponTimeValuee }],
        couponMatch: [{ required: true, validator: checkGoods, trigger: 'blur' }],
        couponAcquireLimitType: [{ required: true }],
        couponAcquireLimit: [{ required: true, validator: checkAcquireLimit, trigger: 'blur' }],
        couponDescription: [
            { required: true, message: '请输入使用说明', trigger: 'blur' }
            // { max: 10, message: '最长不超过200个字', trigger: 'blur' }
        ]
    };
    return { ...baseRuleList };
});

let couponStatus = ref();
const isDisabled = computed(() => {
    const realStatus = couponStatus.value;
    return realStatus && realStatus != 5;
});
const id = computed(() => {
    return route?.query?.id;
});
const couponType = computed(() => {
    const path = route?.path;
    if (/enough/.test(path)) {
        return 1;
    }
    if (/discount/.test(path)) {
        return 2;
    }
    return 1;
});

const couponDiscountMostCheckedChange = val => {
    // 取消最高优惠，couponDiscountMost重置
    if (!val) {
        form.couponDiscountMost = null;
    }
};

const couponPrerequisitesChange = val => {
    clearValidate('couponPrerequisites2');
    clearValidate('couponPrerequisites3');
    if (val == 3) {
        form.couponPrerequisitesAdditional2 = null;
        form.couponEveryDecrease = 1;
        return;
    }
    if (val == 2) {
        form.couponPrerequisitesAdditional3 = null;
        return;
    }
    form.couponEveryDecrease = 1;
    form.couponPrerequisitesAdditional2 = null;
    form.couponPrerequisitesAdditional3 = null;
};

const couponTimeTypeChange = val => {
    if (val == 1) {
        form.couponReceiveTimeTypeVal = null;
        form.couponTimeValue = null;
        return;
    }
    if (val == 2) {
        form.couponTimeAt = [];
        form.couponReceiveTimeTypeVal = 1;
        return;
    }
};

const couponAcquireLimitTypeChange = val => {
    // 领取次数选中改变
    if (val == 1) {
        form.couponAcquireLimit = null;
    }
};

const couponPrerequisitesAdditional2Change = val => {
    validateField('couponDiscountContent');
};

const cancelHandler = () => {
    router.back();
};
const clearValidate = field => {
    unref(addForm).clearValidate(field);
};
const validateField = field => {
    unref(addForm).validateField(field);
};
const getGoodData = data => {
    form.goods.length = 0;
    Object.assign(form.goods, cloneDeep(data));
    validateField('couponMatch');
};
const handleRemoveGood = id => {
    form.goods.splice(form.goods.indexOf(id), 1);
};

const goodTypeChange = val => {
    if (val == 1) {
        form.goods.length = 0;
    }
    validateField('couponMatch');
};
const handleMouseover = e => {
    if (!isDisabled.value) {
        return;
    }
    tooltipVisible.value = true;
    position.value = DOMRect.fromRect({
        width: 0,
        height: 0,
        x: e.clientX,
        y: e.clientY
    });
};
const handleMouseleave = el => {
    if (!isDisabled.value) {
        return;
    }
    tooltipVisible.value = false;
    position.value = {
        top: 0,
        left: 0,
        bottom: 0,
        right: 0
    };
};
// 新增/编辑表单
const saveHandler = async () => {
    if (unref(isPageLoading)) return;
    isPageLoading.value = true;
    if (!unref(addForm)) return;
    await unref(addForm).validate(async (valid, fields) => {
        if (valid) {
            const _form = cloneDeep(form);
            _form.couponType = couponType.value;
            _form.couponDiscountContent = floatMultiply(_form.couponDiscountContent, 100);
            if (_form.couponDiscountMostChecked) {
                _form.couponDiscountMost = floatMultiply(_form.couponDiscountMost, 100);
            } else {
                _form.couponDiscountMost = 0;
            }
            if ([2].includes(_form.couponPrerequisites / 1)) {
                _form.couponPrerequisitesAdditional = floatMultiply(
                    _form[`couponPrerequisitesAdditional${_form.couponPrerequisites}`],
                    100
                );
            }
            if ([3].includes(_form.couponPrerequisites / 1)) {
                _form.couponPrerequisitesAdditional = _form.couponPrerequisitesAdditional3;
            }
            if (_form.couponReceiveTimeTypeVal == 1) {
                _form.couponTimeType = 2;
            } else if (_form.couponReceiveTimeTypeVal == 2) {
                _form.couponTimeType = 3;
            }
            if (_form.couponTimeType == 1) {
                _form.couponTimeStart = format(_form.couponTimeAt[0], 'YYYY-MM-DD HH:mm:ss');
                _form.couponTimeEnd = format(_form.couponTimeAt[1], 'YYYY-MM-DD HH:mm:ss');
            }
            _form.couponAcquireLimit = _form.couponAcquireLimit || 0;
            if (!_form.goods?.length) {
                delete _form.goods;
            }
            Object.keys(_form).forEach(key => {
                if (_form[key] === null) {
                    delete _form[key];
                }
            });
            [
                'couponAcquireLimitType',
                'couponTimeAt',
                'couponReceiveTimeTypeVal',
                'couponPrerequisitesAdditional2',
                'couponPrerequisitesAdditional3',
                'couponDiscountMostChecked'
            ].forEach(key => {
                delete _form[key];
            });
            try {
                const { code, msg } = await request(`couponServ${unref(id) ? 'Edit' : 'Add'}`, _form);
                if (code !== 0) {
                    isPageLoading.value = false;
                    ElMessage({
                        type: 'error',
                        message: msg || '服务异常，请稍后重试'
                    });
                    return;
                }
            } catch (error) {
                ElMessage({
                    type: 'error',
                    message: error?.msg || '服务异常，请稍后重试'
                });
                isPageLoading.value = false;
            }
            isPageLoading.value = false;
            ElMessage({
                type: 'success',
                message: `优惠券${unref(id) ? '编辑' : '创建'}成功`
            });
            cancelHandler();
        } else {
            isPageLoading.value = false;
            unref(addForm).scrollToField(Object.keys(fields)?.[0]);
        }
    });
};

const getDetail = async () => {
    if (unref(id)) {
        const { data } = await request('couponDetailServ', { id: unref(id) });
        const realCoupon = data?.realCoupon || {};
        realCoupon.couponAcquireLimit = realCoupon.couponAcquireLimit || null;
        realCoupon.goods = (realCoupon.goods || [])?.map(item => item.goodsId);
        if ([2].includes(realCoupon.couponPrerequisites / 1)) {
            realCoupon[`couponPrerequisitesAdditional${realCoupon.couponPrerequisites}`] = floatDivide(
                realCoupon.couponPrerequisitesAdditional / 1,
                100
            );
        } else if ([3].includes(realCoupon.couponPrerequisites / 1)) {
            realCoupon[`couponPrerequisitesAdditional${realCoupon.couponPrerequisites}`] =
                realCoupon.couponPrerequisitesAdditional / 1;
        }
        realCoupon.couponDiscountContent = floatDivide(realCoupon.couponDiscountContent, 100);
        realCoupon.couponDiscountMost = realCoupon.couponDiscountMost
            ? floatDivide(realCoupon.couponDiscountMost / 1, 100)
            : null;
        if (realCoupon.couponTimeType == 1) {
            realCoupon.couponTimeAt = [realCoupon.couponTimeStart, realCoupon.couponTimeEnd];
            realCoupon.couponTimeValue = realCoupon.couponTimeValue || null;
            realCoupon.couponReceiveTimeTypeVal = null;
        } else if (realCoupon.couponTimeType == 2) {
            realCoupon.couponReceiveTimeTypeVal = 1;
        } else if (realCoupon.couponTimeType == 3) {
            realCoupon.couponReceiveTimeTypeVal = 2;
            realCoupon.couponTimeType = 2;
        }
        realCoupon.couponAcquireLimitType = realCoupon.couponAcquireLimit ? 2 : 1;
        couponStatus.value = realCoupon.couponStatus;
        // 删除无用的form key值
        const formKeys = Object.keys(form);
        const realCouponKeys = Object.keys(realCoupon);
        const diffKeys = realCouponKeys.filter(item => !formKeys.includes(item));
        diffKeys.forEach(item => {
            delete realCoupon[item];
        });
        realCoupon.id = data?.id;
        realCoupon.couponDiscountMostChecked = !!realCoupon.couponDiscountMost;
        Object.assign(form, realCoupon);
        formClone = cloneDeep(form);
    }
};

onMounted(() => {
    getDetail();
    setLayout();
});
onUnmounted(() => {
    resetLayout();
});
</script>

<style lang="scss">
@import './scss/global.scss';
</style>
<style lang="scss" scoped>
@import './scss/scope.scss';
</style>
